<?php
namespace App\Http\Services;

use App\Http\Model\Hint;
use App\Modules\Relationship\Models\RsRelationshipModel;
use App\Modules\Relationship\Models\RsRelationshipLevelModel;
use App\Http\Model\SystemConfig;
use App\Http\Model\UserLoginLog;
use App\Http\Model\UnionUser;
use App\Http\Model\Union;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\FinanceProxy;
use App\Http\Model\Friends;
use App\Http\Model\Medal;
use App\Http\Model\Room;
use App\Http\Model\RoomUser;
use App\Http\Model\User;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FriendBrowses;
use App\Http\Model\UserProp;
use App\Http\Model\UserBlacklist;
use App\Http\Model\Relation;
use App\Http\Services\MsgServices;


class FriendsServices extends CommonServices
{
    private $model_friends;
    private $model_user;
    private $user_follows;
    private $model_userwallet;
    private $modelMedal;
    private $modelRoomUser;
    private $modelRoom;
    private $userPropModel;
    private $financeProxyModel;
    private $modelUserLoginLog;
    private $rsRelationshipModel;
    private $rsRelationshipLevelModel;
    private $unionUserModel;
    private $unionModel;
    private $financeRechargeOrderModel;
    private $systemConfigModel;
    private $userBlacklistModel;
    protected $relationModel;
    protected $msg_service;
    protected $friendBrowsesModel;

    public function __construct()
    {
        $this->model_friends = new Friends;
        $this->model_user = new User;
        $this->model_userwallet = new FinanceUserWallet;
        $this->modelMedal = new Medal();
        $this->modelRoomUser = new RoomUser();
        $this->modelRoom = new Room();
        $this->userPropModel = new UserProp();
        $this->financeProxyModel = new FinanceProxy();
        $this->modelUserLoginLog = new UserLoginLog();
        $this->rsRelationshipModel = new RsRelationshipModel();
        $this->rsRelationshipLevelModel = new RsRelationshipLevelModel();
        $this->unionUserModel = new UnionUser();
        $this->unionModel = new Union();
        $this->financeRechargeOrderModel = new FinanceRechargeOrder();
        $this->systemConfigModel = new SystemConfig();
        $this->userBlacklistModel = new UserBlacklist();
        $this->relationModel = new Relation();
        $this->msg_service = new MsgServices(); //系统推送通知服务
        $this->friendBrowsesModel = new FriendBrowses();

    }

    /**
     * 获取关注列表
     * @param $user_id
     * @param $page_index 从0开始
     * @param $page_size
     * @return array|null 为null时说明没有数据
     */
    public function get_follows($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
        }
        $follow_count = $this->model_friends->get_follows_count($user_id);
        $follows_limit = $this->model_friends->get_follows_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];
        $map_wallet = [];
        for ($i = 0; $i < count($follows_limit); $i++){
            array_push($list_user_id, $follows_limit[$i]['user_id']);
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        $map_wallet = array_column($wallets, null, 'user_id');

        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++){
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance'] ?? 0);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance'] ?? 0);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance'] ?? 0);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance'] ?? 0);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance'] ?? 0);

            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }
            //获取用户是否在直播间
            $userCurRoom = $this->modelRoomUser->get_user_cur_room($users[$i]['user_id']);
            //查询用户是否使用防跟随道具
            $propUseInfo = $this->userPropModel->getPropUseTime($users[$i]['user_id'], 19);
            $users[$i]['is_room'] = 0;
            $users[$i]['room_id'] = 0;
            $users[$i]['model_str'] = '';
            if (!$propUseInfo) {
                $users[$i]['is_room'] = $userCurRoom ? 1 : 0;
                $users[$i]['room_id'] = $userCurRoom ? intval($userCurRoom) : 0;
                if($userCurRoom){
                    $room_ids[] = $userCurRoom;
                }
            }
            $users[$i]['is_follow'] = $this->model_friends->get_follow_exist_redis($users[$i]['user_id'] ,$user_id) ? true : false;
            $users[$i]['remark_name'] = $this->model_user->getUserRemark($user_id ,$users[$i]['user_id']) ;
        }

        //判断用户是否在房间  update:sn
        if(isset($room_ids)){
            $roomData = $this->modelRoom->get_rooms_by_ids($room_ids);
            foreach ($users as $k=>$v){
                if(!empty($v['room_id'])){
                    $roomId = $v['room_id'];
                    $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                        return $roomId == $param['room_id'];
                    }));
                    $users[$k]['model_str'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                }
            }
        }

        $roomList = array_column($users,'is_room');
        array_multisort($roomList,SORT_DESC, $users);

        $data = [];
        $data['list'] = $users;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($follow_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 获取用户关注 非分页
     * @param $user_id
     * @param $count
     * @return mixed|null
     */
    public function get_follows_nooffset($user_id, $count){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
        }
        $follows_limit = $this->model_friends->get_follows_limit($user_id, 0, $count);

        $list_user_id = [];
        $map_wallet = [];
        for ($i = 0; $i < count($follows_limit); $i++){
            array_push($list_user_id, $follows_limit[$i]['user_id']);
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++){
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance']);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance']);
            $users[$i]['room_type'] = 0;

            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }

        }
        return $users;
    }


    /**
     * 获取粉丝列表
     * @param $user_id
     * @param $page_index
     * @param $page_size
     * @return array|null
     */
    public function get_fans($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
            //清空粉丝数提醒
            $this->model_friends->reset_redis_friends_number($user_id);
        }
        $fans_count = $this->model_friends->get_fans_count($user_id);
        $fans_limit = $this->model_friends->get_fans_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];
        $map_wallet = [];
        for ($i = 0; $i < count($fans_limit); $i++){
            array_push($list_user_id, $fans_limit[$i]['user_id']);
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }
        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++){
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance']);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance']);
            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }
            $users[$i]['is_follow'] = $this->model_friends->get_follow_exist_redis($user_id, $users[$i]['user_id']) ? true : false;

            //获取用户是否在直播间 update:sn
            $userCurRoom = $this->modelRoomUser->get_user_cur_room($users[$i]['user_id']);
            //查询用户是否使用防跟随道具
            $propUseInfo = $this->userPropModel->getPropUseTime($users[$i]['user_id'], 19);
            $users[$i]['is_room'] = 0;
            $users[$i]['room_id'] = 0;
            $users[$i]['model_str'] = '';
            if (!$propUseInfo) {
                $users[$i]['is_room'] = $userCurRoom ? 1 : 0;
                $users[$i]['room_id'] = $userCurRoom ? intval($userCurRoom) : 0;
                if($userCurRoom){
                    $room_ids[] = $userCurRoom;
                }
            }
            $users[$i]['remark_name'] = $this->model_user->getUserRemark($user_id ,$users[$i]['user_id']) ;
        }

        //判断用户是否在房间 update:sn
        if(isset($room_ids)){
            $roomData = $this->modelRoom->get_rooms_by_ids($room_ids);
            foreach ($users as $k=>$v){
                if(!empty($v['room_id'])){
                    $roomId = $v['room_id'];
                    $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                        return $roomId == $param['room_id'];
                    }));
                    $users[$k]['model_str'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                }
            }
        }

        $data = [];
        $data['list'] = $users;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($fans_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }

    /**
     * 获取足迹
     * @param $user_id
     * @param $page_index
     * @param $page_size
     * @return array|null
     */
    public function get_browses($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
        }
        $browses_count = $this->model_friends->get_browses_count($user_id);
        $browses_limit = $this->model_friends->get_browses_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];
        $map_wallet = [];
        $map_browse = [];
        for ($i = 0; $i < count($browses_limit); $i++){
            array_push($list_user_id, $browses_limit[$i]['user_id']);
            $map_browse[$browses_limit[$i]['user_id']] = $browses_limit[$i];
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }
        $users = $this->model_user->get_users_by_ids($list_user_id);

        //道具版本 功能修改
        foreach ($browses_limit as $key => $value) {
            $vUserId = $value['user_id'];
            $findData = array_values(array_filter($users, function ($param) use ($vUserId) {
                return $param['user_id'] == $vUserId;
            }));
            $browses_limit[$key] = $findData ? array_merge($browses_limit[$key], $findData[0]) : $browses_limit[$key];
            $browses_limit[$key]['diamond_balance'] = isset($map_wallet[$vUserId]) ? intval($map_wallet[$vUserId]['diamond_balance']) : 0;
            $browses_limit[$key]['charm_balance'] = isset($map_wallet[$vUserId]) ? intval($map_wallet[$vUserId]['charm_balance']) : 0;
            $browses_limit[$key]['wealth_balance'] = isset($map_wallet[$vUserId]) ? intval($map_wallet[$vUserId]['wealth_balance']) : 0;
            $browses_limit[$key]['reputation_balance'] = isset($map_wallet[$vUserId]) ? intval($map_wallet[$vUserId]['reputation_balance']) : 0;
            $browses_limit[$key]['celebrity_balance'] = isset($map_wallet[$vUserId]) ? intval($map_wallet[$vUserId]['celebrity_balance']) : 0;
            if (array_key_exists(intval($vUserId), $medalData)){
                $browses_limit[$key]['medal'] = $medalData[intval($vUserId)];
            }
            else{
                $browses_limit[$key]['medal'] = [];
            }
            $browses_limit[$key]['browse_timestamp'] = $value['create_timestamp'];
        }

//        for ($i = 0; $i < count($users); $i++){
//            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
//            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
//            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
////            $users[$i]['browse_timestamp'] = intval($map_browse[$users[$i]['user_id']]['create_timestamp']);
//            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance']);
//            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance']);
//            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
//                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
//            }
//            else{
//                $users[$i]['medal'] = [];
//            }
//        }

        $data = [];
        $data['list'] = $browses_limit;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($browses_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     *用户访客列表
     * @param $user_id
     * @param $page_index
     * @param $page_size
     * @return array|null
     */
    public function get_visitors($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
            $this->model_friends->reset_redis_visitor_number($user_id);
        }
        $visitors_count = $this->model_friends->get_visitors_count($user_id);
        $visitors_limit = $this->model_friends->get_visitors_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];
        $map_wallet = [];
        $map_visitor = [];
        for ($i = 0; $i < count($visitors_limit); $i++){
            array_push($list_user_id, $visitors_limit[$i]['user_id']);
            $map_visitor[$visitors_limit[$i]['user_id']] = $visitors_limit[$i];
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++){
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
            $users[$i]['visitor_timestamp'] = intval($map_visitor[$users[$i]['user_id']]['create_timestamp']);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance']);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance']);
            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }
        }


        $data = [];
        $data['list'] = $users;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($visitors_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }

    /**
     * 用户好友列表
     * @param $user_id
     * @param $page_index
     * @param $page_size
     * @return array|null
     */
    public function get_friends($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
        }
        $cur_user_id = $user_id;
        $friends_count = $this->model_friends->get_friends_count($user_id);
        $friends_limit = $this->model_friends->get_friends_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];

        $map_wallet = [];
        for ($i = 0; $i < count($friends_limit); $i++){
            array_push($list_user_id, $friends_limit[$i]['user_id']);
        }

        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        $users = $this->model_user->get_users_by_ids(array_values($list_user_id));
        for ($i = 0; $i < count($users); $i++){
            //检测用户是否已封禁
            $is_forbid = $this->model_user->is_forbid($users[$i]['user_id']);
            if ($is_forbid && $is_forbid == 2){
                $users[$i]['nickname'] = "该用户永久封禁";
                $users[$i]['images'] = User::USER_DEFAULT_IMAGE;
                $users[$i]['thumbnails'] = User::USER_DEFAULT_IMAGE;
            }
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance'] ?? 0);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance'] ?? 0);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance'] ?? 0);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance'] ?? 0);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance'] ?? 0);
            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }

            //获取用户亲密值
            $user_id = $users[$i]['user_id'];
            $findUser = array_values(array_filter($friends_limit, function ($param) use ($user_id) {
                return $param['user_id'] == $user_id;
            }));

            $users[$i]['intimate'] = ($findUser && $findUser[0] && $findUser[0]['intimate']) ? $findUser[0]['intimate'] : 0;

            //获取用户是否在直播间 update:sn
            $userCurRoom = $this->modelRoomUser->get_user_cur_room($users[$i]['user_id']);
            //查询用户是否使用防跟随道具
            $propUseInfo = $this->userPropModel->getPropUseTime($users[$i]['user_id'], 19);
            $users[$i]['is_room'] = 0;
            $users[$i]['room_id'] = 0;
            $users[$i]['model_str'] = '';
            if (!$propUseInfo) {
                $users[$i]['is_room'] = $userCurRoom ? 1 : 0;
                $users[$i]['room_id'] = $userCurRoom ? intval($userCurRoom) : 0;
                if($userCurRoom){
                    $room_ids[] = $userCurRoom;
                }
            }
            //备注
            $users[$i]['remark_name'] = $this->model_user->getUserRemark($cur_user_id ,$users[$i]['user_id']) ;
        }
        //判断用户是否在房间 update:sn
        if(isset($room_ids)){
            $roomData = $this->modelRoom->get_rooms_by_ids($room_ids);
            foreach ($users as $k=>$v){
                if(!empty($v['room_id'])){
                    $roomId = $v['room_id'];
                    $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                        return $roomId == $param['room_id'];
                    }));
                    $users[$k]['model_str'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                }
            }
        }
        $data = [];
        $data['list'] = $users;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($friends_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }

    /**
     * 添加关注
     * @param $follow_user_id
     * @return bool
     */
    public function add_follow($user_id, $follow_user_id){
        $is_follow = $this->model_friends->add_follow($user_id, $follow_user_id);
        if($is_follow>0){
            $data['private_msg'] = '滴滴~我关注你啦';
        }
        $isFriends = $this->model_friends->is_friends($user_id, $follow_user_id);
        $data['is_friends'] = $isFriends;
        if ($isFriends) {
            $this->rsRelationshipModel->insertIfNoExist($user_id, $follow_user_id, 1);
        }
        return $data;
    }

    /**
     * 取消关注
     * @param $follow_user_id
     * @return bool
     */
    public function del_follow($user_id, $follow_user_id){
        $this->model_friends->del_follow($user_id, $follow_user_id);
        $this->model_friends->updateFollowIntimate($follow_user_id, $user_id, 0); //清空好友亲密度
        //判断是否有备注，有备注则删除
        $remark = $this->model_user->getUserRemark($user_id ,$follow_user_id);
        if(!empty($remark)){
            $this->model_user->curdUserRemark(2 ,array('user_id'=>$user_id ,'remark_user_id'=>$follow_user_id));
        }
        $delData = array();
        $delData['userId'] = $user_id;
        $delData['friendId'] = $follow_user_id;
        $delData['type'] = 1;// 取消关注 仅删除普通好友关系
        $this->rsRelationshipModel->deleteRs($delData);
        return true;
    }


    /**
     * 黑名单列表
     * @param $user_id
     * @param $page_index
     * @param $page_size
     * @return array|null
     */
    public function get_blocks($user_id, $page_index, $page_size){
        if(empty($user_id)){
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)){
                return null;
            }
            $user_id = $cur_user['user_id'];
        }
        $blocks_count = $this->model_friends->get_blocks_count($user_id);
        $blocks_limit = $this->model_friends->get_blocks_limit($user_id, $page_index * $page_size, $page_size);

        $list_user_id = [];
        $map_wallet = [];
        for ($i = 0; $i < count($blocks_limit); $i++){
            array_push($list_user_id, $blocks_limit[$i]['user_id']);
        }
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $medalArr = $this->modelMedal->getMedalUserListCache($list_user_id, false);
        $medalData = [];
        foreach ($medalArr as $val){
            if(empty($val)){
                continue;
            }
            $medalData[$val[0]['user_id']] = $val;
        }

        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++){
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
            $users[$i]['reputation_balance'] = intval($map_wallet[$users[$i]['user_id']]['reputation_balance']);
            $users[$i]['celebrity_balance'] = intval($map_wallet[$users[$i]['user_id']]['celebrity_balance']);
            if (array_key_exists(intval($users[$i]['user_id']), $medalData)){
                $users[$i]['medal'] = $medalData[intval($users[$i]['user_id'])];
            }
            else{
                $users[$i]['medal'] = [];
            }
        }

        $data = [];
        $data['list'] = $users;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($blocks_count/$page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 添加黑名单
     * @param $block_user_id
     * @return bool
     */
    public function add_block($block_user_id){
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)){
            return false;
        }
        $user_id = $cur_user['user_id'];
        $this->model_friends->add_block($user_id, $block_user_id);
        return true;
    }

    /**
     * 删除黑名单
     * @param $block_user_id
     * @return bool
     */
    public function del_block($block_user_id){
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)){
            return false;
        }
        $user_id = $cur_user['user_id'];
        $this->model_friends->del_block($user_id, $block_user_id);
        return true;
    }

    /**
     * 判断用户是否上黑名单
     */
    public function getUserInBlock($userId, $toUserId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $data['if_block'] = 0;//是否上黑名单 0=都没上 1=A拉黑B 2=B拉黑A 3=互相拉黑
            $res1 = $this->model_friends->getBlockUserByUserId($userId, $toUserId);
            $res2 = $this->model_friends->getBlockUserByUserId($toUserId, $userId);
            if(!empty($res1) && !empty($res2)) {
                $data['if_block'] = 3;
                break;
            }
            if(!empty($res1)) {
                $data['if_block'] = 1;
                break;
            }
            if(!empty($res2)) {
                $data['if_block'] = 2;
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 添加举报信息
     * @param $report_user_id
     * @param $report_type
     * @param $pics
     * @param $describe
     * @return bool
     */
    public function add_report($loginUserId, $report_user_id, $report_type, $pics, $describe){

        do {
            $this->model_friends->add_report($loginUserId, $report_user_id, $report_type, $pics, $describe);

            //用户是否在黑名单中
            $ifBlack = $this->userBlacklistModel->getBlackListByUserId($report_user_id);
            if($ifBlack) {
                break;
            }

            //私聊及搜索限制配置
            $blackConfig = $this->systemConfigModel->getPrivateMsgBlackConfig();

            //累计充值满足指定金额不受限制
            if(!empty($blackConfig['sms_diamond_num'])) {
                $rechargeNum = $this->financeRechargeOrderModel->getRechargeTotal($report_user_id);
                if($rechargeNum >= $blackConfig['sms_diamond_num']) {
                    break;
                }
            }

            //缓存记录
            $this->userBlacklistModel->setUserBlackCounterReport($loginUserId, $report_user_id);
            //用户校验是否需要加入黑名单
            $blackConfigUse = [];
            $blackConfigUse['report_hour_num'] = empty($blackConfig['report_hour_num']) ? 0 : $blackConfig['report_hour_num'];
            $blackConfigUse['report_user_num'] = empty($blackConfig['report_user_num']) ? 0 : $blackConfig['report_user_num'];
            $ifBlack = $this->userBlacklistModel->userToBlack($report_user_id, $blackConfigUse);
        } while (false);

        return true;
    }


    /**
     * 是否关注
     * @param $follow_user_id
     * @return bool
     */
    public function is_followed($follow_user_id){
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)){
            return false;
        }
        return $this->model_friends->get_follow_exist($cur_user['user_id'], $follow_user_id);
    }


    public function is_blocked($block_user_id){
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)){
            return false;
        }
        return $this->model_friends->get_block_exist($cur_user['user_id'], $block_user_id);
    }


    /**
     * 获取好友关系各种数
     * @return array|int
     */
    public function get_counts(){
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)){
            return Hint::LOGIN_OUT;
        }
        $user_id = $cur_user['user_id'];
        $fans_count = $this->model_friends->get_fans_count($user_id);
        $blocks_count = $this->model_friends->get_blocks_count($user_id);
        $follows_count = $this->model_friends->get_follows_count($user_id);
        $browses_count = $this->model_friends->get_browses_count($user_id);
        $visitors_count = $this->model_friends->get_visitors_count($user_id);
        $friends_count = $this->model_friends->get_friends_count($user_id);

        return ['fans_count' => $fans_count,
            'blocks_count' => $blocks_count,
            'follows_count' => $follows_count,
            'browses_count' => $browses_count,
            'visitors_count' => $visitors_count,
            'friends_count' => $friends_count
        ];
    }

    ################# 后台调用 ##########################################

    /**
     * 用户举报更新
     * */
    public function reportUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '举报ID', 'int', true, '举报ID不能为空');
                $this->I('dispose', '处理类型', 'int', true, '处理类型不能为空');// 0:未处理 1:已处理
                $this->I('dispose_desc', '处理说明', 'string', true, '处理说明不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);
                $this->model_friends->table = 'friends_report';
                $ret = $this->model_friends->singleUpdate(['id' => $id], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '用户举报更新' . Hint::getErrCodeMsg($code);
                    break;
                }

                $data['id'] = intval($id);
                //举报更新发送通知
                //查看举报信息
                $reportInfo = $this->model_friends->getSingle(['id'=>$id],['user_id','report_user_id','describe']);
                //给提出举报的人发系统消息
                $this->msg_service->send_sys_customer_msg($reportInfo[0]['user_id'], $this->requestData['dispose_desc']);
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 查询是否可以发消息权限
     */
    public function getUserRelation($toUserId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            try {
                //登录
                $current_user = $this->model_user->get_current_user();
                if (empty($current_user)) {
                    $code = Hint::LOGIN_OUT;
                    break;
                }
                $userSetInfo1 = $this->model_user->getUserSet($current_user['user_id']);
                $userSetInfo2 = $this->model_user->getUserSet($toUserId);

                $data['is_friends'] = $this->model_friends->is_friends($current_user['user_id'], $toUserId);
                $data['is_follow'] = $this->model_friends->get_follow_exist($current_user['user_id'], $toUserId);
                $data['from_no_msg_friend'] = $userSetInfo1['no_msg_friend'];
                $data['to_no_msg_friend'] = $userSetInfo2['no_msg_friend'];

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    ################# 后台调用 END ##########################################

    /**
     * 获取好友消息数/访客浏览数
     * @return bool
     */
    public function getNoticeNum(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $user = $this->model_user->get_current_user();
            if (empty($user)){
                return Hint::LOGIN_OUT;
            }
            $userId = $user['user_id'];

            $data['browse'] = $this->model_friends->get_redis_visitor_number($userId);
            $data['friends'] = $this->model_friends->get_redis_friends_number($userId);
            $data['finance_proxy'] = $this->financeProxyModel->getRedisFinanceProxyNumber($userId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 删除好友关系 根据uids
     * @param $uids
     * @return bool
     */
    public function removeFriendFollowByUids($uids){
        return $this->model_friends->delFriendsFollowByUids($uids);
    }

    /**
     * 用户发起私聊前校验并获得相互的关系
     */
    public function checkUserSendSms($userId, $toUserId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($userId)) {
                $code = Hint::LOGIN_OUT;
                break;
            }
            if(empty($toUserId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //客服不做限制(临时限制)
            if($toUserId == 18 || $userId == 18){
                $sysInfo = $this->systemConfigModel->getDefaultSystemConfig();
                if(isset($sysInfo['official_show']) && $sysInfo['official_show']['value'] == 0){
                    $code = Hint::SYSTEM_TIP;
                    $msg = '暂不可发起';
                }
                
                break;
            }
            //用户关系
            $data['is_friends'] = $this->model_friends->is_friends($userId, $toUserId);
            $data['is_follow'] = $this->model_friends->get_follow_exist($userId, $toUserId);
            $data['msg_count'] = 10;
            $data['follow_status'] = 0;
            if ($data['is_follow']) {
                $data['follow_status'] = 1;
            }
            if ($data['is_friends']) {
                $data['follow_status'] = 2;
            }
            //添加进白名单的用户不受规则限制
            $whiteConfig = $this->systemConfigModel->getPrivateMsgWhiteConfig();
            if(in_array($userId, $whiteConfig)) {
                break;
            }

            //用户是否在黑名单中
            $ifBlack = $this->userBlacklistModel->getBlackListByUserId($userId);
            if($ifBlack) {
                $code = Hint::SYSTEM_TIP;
                $msg = '暂不可发起';
                break;
            }

            //互相关注的不限制
            if($data['is_friends']) {
                break;
            }

            //发起用户公会ID
            $userUnionId = $this->unionUserModel->getSettleUnionUserIdByUserId($userId);
            if($userUnionId > 0) {
                break;
            }
            //接受用户公会ID
             $toUserUnionId = $this->unionUserModel->getSettleUnionUserIdByUserId($toUserId);
             if($toUserUnionId > 0) {
                 break;
             }

            //私聊及搜索限制配置
            $blackConfig = $this->systemConfigModel->getPrivateMsgBlackConfig();

            //累计充值满足指定金额不受限制
            if(!empty($blackConfig['sms_diamond_num'])) {
                $rechargeNum = $this->financeRechargeOrderModel->getRechargeTotal($userId);
                if($rechargeNum >= $blackConfig['sms_diamond_num']) {
                    break;
                }
            }

            //缓存记录
            $userType = empty($toUserUnionId) ? 1 : 2;
            $this->userBlacklistModel->setUserBlackCounterSms($userId, $toUserId, $userType);
            //用户校验是否需要加入黑名单
            $blackConfigUse = [];
            $blackConfigUse['1_minute_sms_num'] = empty($blackConfig['1_minute_sms_num']) ? 0 : $blackConfig['1_minute_sms_num'];
            $blackConfigUse['5_minute_sms_num'] = empty($blackConfig['5_minute_sms_num']) ? 0 : $blackConfig['5_minute_sms_num'];
            $blackConfigUse['1_day_sms_num'] = empty($blackConfig['1_day_sms_num']) ? 0 : $blackConfig['1_day_sms_num'];
            $ifBlack = $this->userBlacklistModel->userToBlack($userId, $blackConfigUse);
            if($ifBlack > 0) {
                $code = Hint::SYSTEM_TIP;
                $msg = '暂不可发起';
                break;
            }

            $code = Hint::SYSTEM_TIP;
            $msg = '暂不可发起';
            
        } while (false);


        if($code == Hint::SUCCESS) {
            $data['auth'] = 1;
        }else{
            $data['auth'] = [];
        }
        //记录发起私信记录
        $this->model_friends->insertVisitHistory($userId, $toUserId);
        return compact('code', 'msg', 'data');
    }
    
    /**
     *获取浏览记录 
     */
    public function visit_history($userId, $page, $limit, $type){
        $code = Hint::SUCCESS;
        $data = [];
        $msg = '';
        do{
            $result = $this->friendBrowsesModel->get_visit_history($userId, $page, $limit, $type);
            if(!empty($result)){
               foreach($result as $val){
                    if($val['type'] == 1){
                        //查询用户信息
                        $toVisitInfo = $this->model_user->get_user($val['visit_id']);
                        $val['name'] = $toVisitInfo['nickname'];
                        $val['image'] = $toVisitInfo['images'][0];
                        $val['room_type'] = '';
                        $val['icon'] = ''; 
                        $val['visit_time'] = getViewTimeMsg(strtotime($val['visit_time']));
                        $val['count'] = isset($val['count']) ? $val['count'] : 0;
                    }elseif($val['type'] == 2){
                        //查询房间信息
                        $roomInfo = $this->modelRoom->get_room($val['visit_id']);
                        $val['name'] = $roomInfo['name'];
                        $val['image'] = $roomInfo['image'];
                        $val['room_type'] = empty($roomInfo['room_type']['type_name']) ? '男生' : $roomInfo['room_type']['type_name'];
                        $val['icon'] = empty($roomInfo['room_type']['img_home_url']) ? '' : $roomInfo['room_type']['img_home_url'];
                        $val['visit_time'] = getViewTimeMsg(strtotime($val['visit_time']));
                        $val['count'] = isset($val['count']) ? $val['count'] : 0;
                    }
                    $data[] = $val;
                    unset($val);
               }
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 获取用户亲密关系列表
     */
    public function getUserRelationList($userId, $toUserId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $now = time();

        do {
            if(empty($toUserId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //用户信息
            $userInfo = $this->model_user->get_user($toUserId);
            $data['user_info'] = [
                'user_id' => $userInfo['user_id'],
                'user_uid' => $userInfo['user_uid'],
                'nickname' => $userInfo['nickname'],
                'gender' => $userInfo['gender'],
                'images' => $userInfo['images']
            ];

            //亲密关系列表
            $list = [];
            $relationList = $this->relationModel->getUserRelationAll($toUserId);
            if(!empty($relationList)) {
                $userIds = array_merge(array_column($relationList, 'user_id_1'), array_column($relationList, 'user_id_2'));
                $userList = $this->model_user->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $rankList = $this->relationModel->getRelationRank();
                $rankList = array_column($rankList, null, 'rank_id');

                foreach($relationList as $val) {
                    $rUserId = ($val['user_id_1']==$toUserId) ? $val['user_id_2'] : $val['user_id_1'];
                    if(empty($userList[$rUserId]) || empty($rankList[$val['rank_id']])) {
                        continue;
                    }
                    $userInfo = $userList[$rUserId];
                    $rankInfo = $rankList[$val['rank_id']];
                    $item = [];
                    $item['user_info'] = [
                        'user_id' => $userInfo['user_id'],
                        'user_uid' => $userInfo['user_uid'],
                        'nickname' => $userInfo['nickname'],
                        'gender' => $userInfo['gender'],
                        'images' => $userInfo['images']
                    ];
                    $item['rank_id'] = $val['rank_id'];
                    $item['rank_name'] = $rankInfo['rank_name'];
                    $item['image'] = $rankInfo['image'];
                    $item['colour'] = $rankInfo['colour'];
                    $item['less_num'] = $val['end_time'] - $now;
                    $item['start_time'] = date('Y.m.d', $val['start_time']);
                    $item['end_time'] = date('Y.m.d', $val['end_time']);

                    $list[] = $item;
                }
            }
            $data['list'] = $list;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取用户列表
    public function getFriendList($userId, $pageIndex = 0, $pageSize = 10, $haveRs = 0): array {
        $data = [];
        $rows = $this->rsRelationshipModel->getList($userId, $pageIndex * $pageSize, $pageSize, $haveRs);
        $cou = $this->rsRelationshipModel->getListCount($userId, $haveRs);
        $levels = $this->rsRelationshipLevelModel->getAllLevel();
        if (count($rows) > 0) {
            // 获取全部uid
            $friendIds = array_column($rows, 'friendId');
            $friends = $this->model_user->get_users_by_ids($friendIds);
            $idxIdFriends = array_column($friends, null, 'user_id');
            $medalArr = $this->modelMedal->getMedalUserListCache($friendIds, false);
            $medalData = [];
            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
            $continueRow = [];
            foreach ($rows as $row) {
                $f = $idxIdFriends[$row->friendId];
                if ($f != null) {
                    $userIntimate = $this->model_friends->getFriendIntimate($userId, $row->friendId);

                    $curLevel = $this->rsRelationshipLevelModel->getLevelByIntimate($userIntimate, $row->type);
                    // 获取
                    $levelIdkey = $row->type . '_' . $curLevel['level'];
                    if (!$levels[$levelIdkey]){
                        $continueRow[] = ['user_id' => $userId, 'friend_id'=>$row->friendId, 'levelIdkey'=>$levelIdkey];
                        continue;
                    }
                    $dataItem = [];
                    $dataItem['id'] = $row->id;
                    $dataItem['userId'] = $f['user_id'];
                    $dataItem['userUid'] = $f['user_uid'];
                    $dataItem['nickname'] = $f['nickname'];
                    $dataItem['gender'] = $f['gender'];
                    $dataItem['sign'] = $f['sign'];
                    $dataItem['adapt_images'] = $f['adapt_images'][0];
                    $dataItem['images'] = $f['images'][0];
                    $dataItem['thumbnails'] = $f['thumbnails'][0];
                    $dataItem['type'] = $row->type;

                    $dataItem['levelName'] = $levels[$levelIdkey]['levelName'];
                    $dataItem['levelImg'] = build_url($levels[$levelIdkey]['levelImg']);
                    $dataItem['intimate'] = $userIntimate;
                    $dataItem['isRoom'] = 0;
                    $dataItem['roomId'] = 0;
                    if (array_key_exists(intval($f['user_id']), $medalData)){
                        $dataItem['medal'] = $medalData[intval($f['user_id'])];
                    }
                    else{
                        $dataItem['medal'] = [];
                    }

                    $dataItem['modelStr'] = "";
                    //获取用户是否在直播间 update:sn
                    $userCurRoom = $this->modelRoomUser->get_user_cur_room($f['user_id']);
                    //查询用户是否使用防跟随道具
                    $propUseInfo = $this->userPropModel->getPropUseTime($f['user_id'], 19);
                    if (!$propUseInfo) {
                        $dataItem['isRoom'] = $userCurRoom ? 1 : 0;
                        $dataItem['roomId'] = $userCurRoom ? intval($userCurRoom) : 0;
                        if($userCurRoom){
                            $roomIds[] = $userCurRoom;
                        }
                    }
                    $dataItem['remarkName'] = $this->model_user->getUserRemark($userId, $f['user_id']);
                    $data[] = $dataItem;
                }
            }
            // write_log(
            //     'RsCommonService'.(isCli()?'-cli':''),
            //     '[INFO] 好友关系-formatFriendList',
            //     ['userId'=>$userId, 'continueRow'=>$continueRow]
            // );
        }

        $dataList =  array_values($data);
        //判断用户是否在房间 update:sn
        if(isset($roomIds)){
            $roomData = $this->modelRoom->get_rooms_by_ids($roomIds);
            foreach ($dataList as $k=>$v){
                if(!empty($v['roomId'])){
                    $roomId = $v['roomId'];
                    $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                        return $roomId == $param['roomId'];
                    }));
                    $dataList[$k]['modelStr'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                }
            }
        }
        $return = [];
        $return['list'] = array_values($dataList);
        $return['pageIndex'] = $pageIndex;
        $return['pageCount'] = ceil($cou/$pageSize);
        $return['pageSize'] = intval($pageSize);
        return $return;
    }


}
